// pages/newlist/newlist.js
const db = wx.cloud.database().collection('xinwen')
const db2 = wx.cloud.database().collection('pinglun')
Page({

  data: {
    title: '',
    datalist: [],
    show: true,
    show2: false,
    pinData: '',
    id: '',
    pinDataList: []
  },

  onLoad: function (options) {
    this.setData({
      title: options.title,
      id: options.id
    })
    this.getData ()
  },
  getData () { // 获取数据
    let thiss = this
    db.get({
      success (res) {
        var data = res.data
        for(let i=0;i<data.length;i++){
          if(data[i].title === thiss.data.title){
            thiss.setData({
              datalist:data[i]
            })
          }
        }
      }
    })

    var listData = []
    db2.get({
      success (res) {
        for (let i=0; i<res.data.length; i++) {
          if (res.data[i].id === thiss.data.id) {
            listData.push(res.data[i])
          }
        }
        thiss.setData({
          pinDataList: listData
        })
      }
    })
  },
  getPin (data) {
    this.setData ({
      pinData: data.detail.value
    })
    if (this.data.pinData) {
      this.setData ({
        show: false,
        show2: true
      })
      console.log('显示按钮')
    }
    if (!this.data.pinData) {
      this.setData ({
        show: true,
        show2: false
      })
      console.log('关闭按钮')
    }
  },
  relPin () {
    let thiss = this
    wx.showLoading({
      title: "排队中...." ,
      mask: true,
    })
    db2.add({
      data: {
        content: this.data.pinData,
        image: wx.getStorageSync('userInfo').avatarUrl,
        name: wx.getStorageSync('userInfo').nickName,
        id: this.data.id
      },
      success (res) {
        console.log(res)
        var listData = []
        db2.get({
          success (res) {
            for (let i=0; i<res.data.length; i++) {
              if (res.data[i].id === thiss.data.id) {
                listData.push(res.data[i])
              }
            }
            thiss.setData({
              pinDataList: listData
            })
            wx.showToast({
              title: '发布成功...',
              icon: 'none'
            })
            wx.hideLoading()
            thiss.setData ({
              show: true,
              show2: false
            })
            thiss.setData ({
              textInputValue: ''
            })
          }
        })
      },
      fail (err) {
        console.log(err)
      }
    })
  }
})